package cn.chiship.framework.upms.biz.user.service.impl;

import cn.chiship.framework.upms.biz.user.entity.UpmsPermission;
import cn.chiship.framework.upms.biz.user.entity.UpmsPermissionExample;
import cn.chiship.framework.upms.biz.user.mapper.UpmsPermissionMapper;
import cn.chiship.framework.upms.biz.user.service.UpmsPermissionService;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.enums.BaseResultEnum;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.core.util.http.ResponseUtil;
import cn.chiship.sdk.framework.base.BaseServiceImpl;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Locale;

/**
 * 权限业务接口实现层 2021/9/27
 *
 * @author lijian
 */
@Service
public class UpmsPermissionServiceImpl extends BaseServiceImpl<UpmsPermission, UpmsPermissionExample>
        implements UpmsPermissionService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UpmsPermissionServiceImpl.class);

    @Resource
    UpmsPermissionMapper upmsPermissionMapper;

    @Override
    public BaseResult changeIsState(String id, Boolean isDisabled) {
        UpmsPermission permission = upmsPermissionMapper.selectByPrimaryKey(id);
        permission.setGmtModified(System.currentTimeMillis());
        permission.setIsDisabled(Boolean.TRUE.equals(isDisabled) ? BaseConstants.YES : BaseConstants.NO);
        boolean flag = upmsPermissionMapper.updateByPrimaryKeySelective(permission) > 0;
        if (!flag) {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_UPDATE, null);
        } else {
            return BaseResult.ok();
        }
    }

    @Override
    public BaseResult insertSelective(UpmsPermission upmsPermission) {
        upmsPermission.setIsDisabled(BaseConstants.NO);
        UpmsPermissionExample upmsPermissionExample = new UpmsPermissionExample();
        upmsPermissionExample.createCriteria().andPermissionValueEqualTo(upmsPermission.getPermissionValue())
                .andTypeEqualTo(upmsPermission.getType());
        List<UpmsPermission> ucPermissions = upmsPermissionMapper.selectByExample(upmsPermissionExample);
        if (ucPermissions.isEmpty()) {
            return super.insertSelective(upmsPermission);
        } else {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_REPEAT, "菜单编码或权限值已存在,请重新输入");
        }
    }

    @Override
    public BaseResult updateByPrimaryKeySelective(UpmsPermission upmsPermission) {
        UpmsPermissionExample upmsPermissionExample = new UpmsPermissionExample();
        upmsPermissionExample.createCriteria().andPermissionValueEqualTo(upmsPermission.getPermissionValue())
                .andTypeEqualTo(upmsPermission.getType()).andIdNotEqualTo(upmsPermission.getId());
        List<UpmsPermission> ucPermissions = upmsPermissionMapper.selectByExample(upmsPermissionExample);
        if (ucPermissions.isEmpty()) {
            return super.updateByPrimaryKeySelective(upmsPermission);
        } else {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_REPEAT, "菜单编码或权限值已存在,请重新输入");
        }
    }

    @Override
    public void downloadPermissionCode(HttpServletResponse response, Byte category) {
        try {
            StringBuilder builder = new StringBuilder();
            builder.append("// 若前端使用此文件,请将此文件所有编码复制到[src/utils/allPermission.js]下\n");
            UpmsPermissionExample upmsPermissionExample = new UpmsPermissionExample();
            UpmsPermissionExample.Criteria criteria = upmsPermissionExample.createCriteria().andTypeEqualTo(Byte.valueOf("2"));
            if (!StringUtil.isNull(category)) {
                criteria.andCategoryEqualTo(category);
            }
            upmsPermissionExample.setOrderByClause("permission_value desc");
            List<UpmsPermission> upmsPermissions = super.selectByExample(upmsPermissionExample);
            for (UpmsPermission p : upmsPermissions) {
                JSONObject jb = new JSONObject();
                jb.put("// ", p.getName());
                builder.append("// " + p.getName() + "\n");
                builder.append(p.getPermissionValue().replace(":", "_").replace(".", "_").toUpperCase(Locale.ROOT)
                        + ":'" + p.getPermissionValue() + "',\n");
            }
            response.setContentType("text/plain;charset=utf-8");
            ResponseUtil.setAttachmentResponseHeader(response, "权限编码.js");
            OutputStream os = response.getOutputStream();
            os.write(builder.toString().getBytes(StandardCharsets.UTF_8));
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
